<template>
  <div class="login-container">
    <div class="login-box">
      <h2>登录到 npm-explore</h2>
      <el-form ref="loginForm" :model="loginForm" :rules="rules" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入用户名" autocomplete="username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" autocomplete="current-password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin" :loading="loginLoading">登录</el-button>
          <el-button @click="$router.push('/register')" v-if="showRegister">注册</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: 'LoginPage',
  data() {
    return {
      loginForm: {
        username: 'admin', // 默认用户名
        password: 'admin123' // 默认密码
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      },
      loginLoading: false,
      showRegister: true // 是否显示注册按钮
    }
  },
  computed: {
    // 从store中获取登录加载状态
    loginLoading() {
      return this.$store.state.auth.loginLoading
    }
  },
  methods: {
    // 处理登录
    handleLogin() {
      this.$refs.loginForm.validate(async (valid) => {
        if (valid) {
          try {
            // 调用登录action
            await this.$store.dispatch('auth/login', this.loginForm)
          } catch (error) {
            this.$message.error('登录失败，请重试')
            console.error('Login failed:', error)
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.login-box {
  width: 400px;
  padding: 40px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.login-box h2 {
  text-align: center;
  margin-bottom: 30px;
  color: #303133;
}

.el-button + .el-button {
  margin-left: 10px;
}
</style>